/*
 *  Copyright 2013 Utkin Dmitry
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include <QMutex>
#include <QWaitCondition>

#include "BlockingClosure.h"

namespace protoqtrpc
{

class BlockingClosurePrivate
{
public:
    QMutex mutex;
    QWaitCondition waitCond;
    bool done;

    BlockingClosurePrivate():
        done(false)
    {
    }
};

BlockingClosure::BlockingClosure():
    d_ptr(new BlockingClosurePrivate)
{
}

BlockingClosure::~BlockingClosure()
{
    delete d_ptr;
}

void BlockingClosure::Run()
{
    QMutexLocker lock(&d_ptr->mutex);
    d_ptr->done = true;
    d_ptr->waitCond.wakeAll();
}

bool BlockingClosure::hasRun() const
{
    return d_ptr->done;
}

void BlockingClosure::reset()
{
    QMutexLocker lock(&d_ptr->mutex);
    d_ptr->done = false;
}

bool BlockingClosure::wait(unsigned long time /*= 0*/)
{
    QMutexLocker lock(&d_ptr->mutex);
    if (!d_ptr->done)
        return d_ptr->waitCond.wait(&d_ptr->mutex, time ? time : ULONG_MAX);

    return true;
}

}
